

package com.kimo.shop.admin.controller;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.model.Category;
import com.kimo.shop.bean.model.RetailProd;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.service.CategoryService;
import com.kimo.shop.service.RetailProdService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 * @author kimo-taozhouchuan
 * @date 2020-08-24 15:18:35
 */
@RestController
@AllArgsConstructor
@RequestMapping("/shop/retailProd" )
public class RetailProdController {

    private final RetailProdService retailProdService;
    private final Snowflake snowflake;
    private final CategoryService categoryService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param retailProd
     * @return 分页数据
     */
    @GetMapping("/page" )
    public ResponseEntity<IPage<RetailProd>> getRetailProdPage(PageParam<RetailProd> page, RetailProd retailProd) {
        retailProd.setShopId(Constant.PLATFORM_SHOP_ID);
        return ResponseEntity.ok(retailProdService.getPage(page, retailProd));
    }


    /**
     * 通过id查询
     * @param retailProdId id
     * @return 单个数据
     */
    @GetMapping("/info/{retailProdId}" )
    public ResponseEntity<RetailProd> getById(@PathVariable("retailProdId") Long retailProdId) {
        return ResponseEntity.ok(retailProdService.getInfo(retailProdId));
    }

    /**
     * 新增
     * @param retailProd
     * @return 是否新增成功
     */
    @PostMapping
    public ResponseEntity<Boolean> save(@RequestBody @Valid RetailProd retailProd) {
        retailProd.setCreateTime(new Date());
        retailProd.setShopId(Constant.PLATFORM_SHOP_ID);
        if (StrUtil.isBlank(retailProd.getBarCode())) {
            String barcode = StringUtils.join("P", String.valueOf(snowflake.nextId()));
            retailProd.setBarCode(barcode);
        } else {
            retailProdService.countBarCode(retailProd.getBarCode());
        }
        checkCategory(retailProd.getCategoryId());
        return ResponseEntity.ok(retailProdService.save(retailProd));
    }

    /**
     * 校验商品的三级分类
     * @param categoryId
     */
    private void checkCategory(Long categoryId) {
        if (categoryId != null) {
            Category category = categoryService.getById(categoryId);
            if (category != null && category.getGrade() != 2) {
                throw new KimoShopBindException("商品分类需选择三级分类");
            }
        }
    }

    /**
     * 修改
     * @param retailProd
     * @return 是否修改成功
     */
    @PutMapping
    public ResponseEntity<Boolean> updateById(@RequestBody @Valid RetailProd retailProd) {
        retailProd.setUpdateTime(new Date());
        if (StrUtil.isBlank(retailProd.getBarCode())) {
            retailProd.setBarCode(StringUtils.join("P",String.valueOf(snowflake.nextId())));
        } else {
            retailProdService.countBarCodeAndId(retailProd.getBarCode(),retailProd.getRetailProdId());
        }
        checkCategory(retailProd.getCategoryId());
        boolean update =  retailProdService.updateAndUpdateStock(retailProd);
        return ResponseEntity.ok(update);
    }

    /**
     * 通过ids删除
     * @return 是否删除成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> removeById(@RequestBody Long[] ids) {
        retailProdService.removeRetainProdByIds(ids,Constant.PLATFORM_SHOP_ID);
        return ResponseEntity.ok().build();
    }

    /**
     * 导出单品商品  筛选条件
     */
    @GetMapping("/exportRetailProd")
    public void exportProd(RetailProd retailProd, HttpServletResponse response) {
        retailProdService.exportRetailProd(retailProd,response,Constant.PLATFORM_SHOP_ID);
    }
    /**
     * 单品商品导入模板
     */
    @GetMapping("/importRetailProdModel")
    public void importRetailProdModel(HttpServletResponse response) {
        retailProdService.importRetailProdModel(response,Constant.PLATFORM_SHOP_ID);
    }

    @ApiOperation(value = "导入文件")
    @PostMapping("/importExcel")
    @ResponseBody
    public ResponseEntity importExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {
        if(Objects.isNull(excelFile)) {
            // 网络繁忙，请稍后重试
            throw new KimoShopBindException("kimo.network.busy");
        }
        return ResponseEntity.ok(retailProdService.parseFile(excelFile,Constant.PLATFORM_SHOP_ID));
    }

}
